<template>
  <div class="application-form-container">
    <div class="application-form">
      <div class="header-left">
        <router-link to="/main/renshi/jixiao" class="back-btn">
          <i class="el-icon-arrow-left"></i> 返回
        </router-link>
        <div class="save-info">
          <el-button type="primary" icon="el-icon-check" @click="saveForm">保存</el-button>
          <el-button type="primary" icon="el-icon-check" @click="goToList">列表</el-button>
          <el-button type="info" icon="el-icon-printer" @click="printForm">打印</el-button>
        </div>
      </div>
      <h2 style="text-align: center;">文件新增/修订/废止申请单</h2>
      <table class="clauses-table">
        <tr>
          <td>
            <span>申请日期：</span>
          </td>
          <td title="双击可修改" colspan="2">
            <template v-if="editingFields.applyDate">
              <input type="date" v-model="applyDate" @blur="stopEditing('applyDate')">
            </template>
            <template v-else>
              <span @dblclick="startEditing('applyDate')">{{ applyDate }}</span>
            </template>
          </td>
          <td>
            <span>申请部门：</span>
          </td>
          <td title="双击可修改" colspan="2">
            <template v-if="editingFields.applyDepartment">
              <input type="text" v-model="applyDepartment" @blur="stopEditing('applyDepartment')">
            </template>
            <template v-else>
              <span @dblclick="startEditing('applyDepartment')">{{ applyDepartment }}</span>
            </template>
          </td>
          <td>
            <span>申请人：</span>
          </td>
          <td title="双击可修改" colspan="2">
            <template v-if="editingFields.applicant">
              <input type="text" v-model="applicant" @blur="stopEditing('applicant')">
            </template>
            <template v-else>
              <span @dblclick="startEditing('applicant')">{{ applicant }}</span>
            </template>
          </td>
        </tr>
        <tr>
          <td>
            <span>文件名称：</span>
          </td>
          <td title="双击可修改" colspan="3">
            <template v-if="editingFields.fileName">
              <input type="text" v-model="fileName" @blur="stopEditing('fileName')">
            </template>
            <template v-else>
              <span @dblclick="startEditing('fileName')">{{ fileName }}</span>
            </template>
          </td>
          <td>
            <span>文件编号：</span>
          </td>
          <td title="双击可修改" colspan="2">
            <template v-if="editingFields.fileNumber">
              <input type="text" v-model="fileNumber" @blur="stopEditing('fileNumber')">
            </template>
            <template v-else>
              <span @dblclick="startEditing('fileNumber')">{{ fileNumber }}</span>
            </template>
          </td>
          <td>
            <span>版本：</span>
          </td>
          <td title="双击可修改">
            <template v-if="editingFields.version">
              <input type="text" v-model="version" @blur="stopEditing('version')">
            </template>
            <template v-else>
              <span @dblclick="startEditing('version')">{{ version }}</span>
            </template>
          </td>
        </tr>
      </table>
      <table class="clauses-table">
        <thead>
          <tr>
            <td style="border-top: 0px;">
              <span>申请类别</span>
            </td>
            <td colspan="2" style="border-top: 0px;">
              <el-radio-group v-model="applyType">
                <el-radio label="新增">新增</el-radio>
                <el-radio label="修订">修订</el-radio>
                <el-radio label="废止">废止</el-radio>
              </el-radio-group>
            </td>
          </tr>
          <tr>
            <td>
              <span>申请原因</span>
            </td>
            <td colspan="2">
              <textarea v-model="applyReason"></textarea>
            </td>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>具体条款</td>
            <td>原文件内容</td>
            <td>现文件内容</td>
          </tr>
          <tr>
            <td><input type="text" v-model="clauseItem.clause" /></td>
            <td><textarea v-model="clauseItem.originalContent"></textarea></td>
            <td><textarea v-model="clauseItem.currentContent"></textarea></td>
          </tr>
        </tbody>
      </table>
      <table class="clauses-table">
        <tr>
          <th colspan="5" style="border-top: 0px;">
            <span>会审意见</span>
          </th>
        </tr>
        <tr v-for="(opinion, index) in reviewOpinionList" :key="index">
          <td class="department-cell">
            <span>{{ opinion.department }}</span>
          </td>
          <td colspan="4">
            <span style="display: flex;margin-left: 30px;">
              <label><input type="radio" v-model="opinion.approve" value="同意"> 同意</label>&emsp;&emsp;
              <label><input type="radio" v-model="opinion.approve" value="不同意"> 不同意</label>
            </span><br>
            <span style="display: inline-flex; ">主要意见是：
              <textarea rows="5" cols="100" v-model="opinion.comment"></textarea></span><br>
            <span style="display: flex;
align-items: center;
justify-content: flex-end;padding: 10px 0px;">
              <span>会审人：</span>
              <input type="text" v-model="opinion.reviewer">
              <span>日期：</span>
              <input type="date" v-model="opinion.date">
            </span>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <span class="explanation">
              <span>说明：1、各会审人需在两个工作日内回复，未作回复则视同认可。2、表单不用经各会审意见。</span>
            </span>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
import { getDocumentRevisionDetail, saveDocumentRevision } from '@/api/document-revision'

export default {
  name: 'DocumentApplicationForm',
  data() {
    return {
      id: null,
      applyDate: new Date().toISOString().substr(0,10),
      applyDepartment: '',
      applicant: '',
      fileName: '',
      fileNumber: '',
      version: '',
      applyType: '新增',
      applyReason: '',
      clauseItem: {
        clause: '',
        originalContent: '',
        currentContent: ''
      },
      reviewOpinionList: [
        {
          department: '企业管理部',
          approve: '',
          comment: '',
          reviewer: '',
          date: ''
        },
        { department: '总经理室', approve: '', comment: '', reviewer: '', date: '' },
        { department: '管理者代表', approve: '', comment: '', reviewer: '', date: '' },
        { department: '财务管理部', approve: '', comment: '', reviewer: '', date: '' },
        { department: '工会', approve: '', comment: '', reviewer: '', date: '' },
        { department: '手机事业部', approve: '', comment: '', reviewer: '', date: '' },
        { department: '光电事业部', approve: '', comment: '', reviewer: '', date: '' },
      ],
      editingFields: {
        applyDate: false,
        applyDepartment: false,
        applicant: false,
        fileName: false,
        fileNumber: false,
        version: false
      },
      viewOnly: false
    };
  },
  created() {
    const { id, type } = this.$route.query
    if (id) {
      this.getDetail(id)
    }
    this.viewOnly = type === 'view'
  },
  methods: {
    startEditing(field) {
      this.editingFields[field] = true;
    },
    stopEditing(field) {
      this.editingFields[field] = false;
    },
    printForm() {
      window.print()
    },
    getDetail(id) {
      getDocumentRevisionDetail(id).then(response => {
        console.log('获取详情响应:', response)
        if (response.data.data) {
          const data = response.data.data
          // 基本信息
          this.id = data.id
          this.applyDate = data.applyDate
          this.applyDepartment = data.applyDepartment
          this.applicant = data.applicant
          this.fileName = data.fileName
          this.fileNumber = data.fileNumber
          this.version = data.version
          this.applyType = data.applyType
          this.applyReason = data.applyReason

          // 条款信息
          this.clauseItem = {
            clause: data.clauseItem || '',
            originalContent: data.originalContent || '',
            currentContent: data.currentContent || ''
          }

          // 审批意见列表
          if (data.reviewList && data.reviewList.length > 0) {
            // 使用现有的部门列表结构，但更新其中的值
            const reviewMap = new Map(data.reviewList.map(item => [item.department, item]))
            
            this.reviewOpinionList = this.reviewOpinionList.map(item => {
              const existingReview = reviewMap.get(item.department)
              if (existingReview) {
                return {
                  department: item.department,
                  approve: existingReview.approveStatus || '',
                  comment: existingReview.comment || '',
                  reviewer: existingReview.reviewer || '',
                  date: existingReview.reviewDate || ''
                }
              }
              return item
            })
          }
        }
      })
    },
    goToList() {
      this.$router.push({
        name: 'WjxiudinsqdList',
        query: {
          type: 'view'
        }
      })
    },  
    saveForm() {
      // 表单验证
      if (!this.applyDate) {
        this.$message.error('申请日期不能为空')
        return
      }
      if (!this.applyDepartment) {
        this.$message.error('申请部门不能为空')
        return
      }
      if (!this.applicant) {
        this.$message.error('申请人不能为空')
        return
      }
      if (!this.fileName) {
        this.$message.error('文件名称不能为空')
        return
      }
      if (!this.fileNumber) {
        this.$message.error('文件编号不能为空')
        return
      }

      // 构造与后端实体对应的数据结构
      const formData = {
        id: this.id,
        applyDate: this.applyDate,
        applyDepartment: this.applyDepartment,
        applicant: this.applicant,
        fileName: this.fileName,
        fileNumber: this.fileNumber,
        version: this.version,
        applyType: this.applyType,
        applyReason: this.applyReason,
        clauseItem: this.clauseItem.clause,
        originalContent: this.clauseItem.originalContent,
        currentContent: this.clauseItem.currentContent,
        status: '待审核',
        reviewList: this.reviewOpinionList.map(item => ({
          department: item.department,
          approveStatus: item.approve,
          comment: item.comment,
          reviewer: item.reviewer,
          reviewDate: item.date
        }))
      }

      console.log('提交的表单数据:', formData)

      saveDocumentRevision(formData).then(response => {
        console.log('保存响应:', response)
        if (response.data.code === 200) {
          this.$message.success('保存成功')
          this.$router.push('/main/renshi/jixiao/wjxiudinsqdList')
        } else {
          this.$message.error(response.data.message || '保存失败')
        }
      }).catch(error => {
        console.error('保存失败:', error)
        this.$message.error('保存失败：' + (error.message || '未知错误'))
      })
    }
  }
};
</script>

<style scoped lang="scss">
.application-form-container {
  font-family: '宋体', sans-serif;
  padding: 20px;
}

.application-form {
  width: 1200px;
  margin: 0 auto;
}

.header-left {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  color: #409EFF;

  i {
    font-size: 20px;
    color: #409EFF;
  }

  a.back-btn.router-link-active {
    color: #409EFF;
    display: flex;
    align-items: center;
  }
}

.form-info {
  display: flex;
  margin-bottom: 15px;
}

.info-item {
  margin-right: 30px;
}

.apply-details {
  margin-bottom: 15px;
}

.category,
.reason {
  margin-bottom: 10px;
}

.clauses-table {
  width: 100%;
  border-collapse: collapse;
  /* margin-bottom: 15px; */
}

.clauses-table th,
.clauses-table td {
  border: 1px solid #000;
  padding: 8px;
  text-align: center;
}

.review-opinions {
  margin-bottom: 15px;
}

.opinion-item {
  margin-bottom: 10px;
}

.explanation {
  margin-bottom: 15px;
}

.save-info {
  margin-top: 15px;
}

.save-info button {
  padding: 8px 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
}

.department-cell {
  width: 200px;
  text-align: center;
  vertical-align: middle;
}

@media print {
  .application-form {
    width: 1000px;
    margin: 0px;
  }

  .header-left {
    display: none;
  }

  .department-cell {
    width: 100px;
  }

  table {
    margin: 0px 0px;
  }

  .info-table,
  .content-table,
  .approval-table {
    border: 1px solid #000;

    td,
    th {
      border: 1px solid #000;
    }
  }

  td,
  th {
    padding: 5px;
    border: 1px solid #000;
  }

  input {
    border: none !important;
    background-color: transparent !important;
    text-align: center;
  }

  textarea {
    border: 0px !important;
    width: 80%;
    padding: 5px;
    height: 50px;
    max-height: 900px;
  }
}

.el-radio-group {
  display: flex;
  gap: 20px;
}
.el-radio {
  margin-right: 20px;
}
</style>